package xps.and.uudaijia.userclient.view.activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.bumptech.glide.Glide;
import com.jude.utils.JUtils;
import com.zhy.autolayout.AutoLinearLayout;

import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import jp.wasabeef.glide.transformations.CropCircleTransformation;
import rx.Subscriber;
import xps.and.uudaijia.userclient.R;
import xps.and.uudaijia.userclient.aly.OssService;
import xps.and.uudaijia.userclient.aly.STSGetter;
import xps.and.uudaijia.userclient.aly.UIDisplayer;
import xps.and.uudaijia.userclient.data.baen.SmsResponce;
import xps.and.uudaijia.userclient.data.net.UserNetWorks;
import xps.and.uudaijia.userclient.util.DensityUtil;
import xps.and.uudaijia.userclient.view.base.BaseActivity;

/**
 * Created by Administrator on 2017/7/24.
 */

public class ModifyMeActivity extends BaseActivity {
    @BindView(R.id.actionbar_iv_back)
    ImageView actionbarIvBack;
    @BindView(R.id.touxiang_Img)
    ImageView touxiangImg;
    @BindView(R.id.dianji_Layout)
    AutoLinearLayout dianjiLayout;
    @BindView(R.id.Name_Text)
    TextView NameText;
    @BindView(R.id.XM_Layout)
    AutoLinearLayout XMLayout;
    @BindView(R.id.Gender_Text)
    TextView GenderText;
    @BindView(R.id.XB_Layout)
    AutoLinearLayout XBLayout;
    @BindView(R.id.DianHua_Text)
    TextView dianhuaText;
    private UIDisplayer displayer;
    private OssService ossService;
    private static final String endpoint = "http://oss-cn-beijing.aliyuncs.com";
    private static final String callbackAddress = "http://api.xn--uu-df3cl18z.com/v1/main/oss-call-back";
    private static final String bucket = "";
    private String picturePath = "";
    private static final int RESULT_LOAD_IMAGE = 1;
    String User_Phone = "";
    String headImg = "";
    String CheckBoxString;
    String SJ_name;
    String SJ_sex;

    @Override
    protected int getLayout() {
        return R.layout.activity_modifyme;
    }

    @Override
    protected void setData() {

    }

    @Override
    protected void init() {
        ButterKnife.bind(this);
        headImg = JUtils.getSharedPreference().getString("User_Img", "");
        Log.e("headImg", headImg);
        SJ_name = JUtils.getSharedPreference().getString("User_name", "");
        SJ_sex = JUtils.getSharedPreference().getString("User_sex", "");
        displayer = new UIDisplayer(this);
        ossService = initOSS(endpoint, displayer);
        ossService.setCallbackAddress(callbackAddress);
        SharedPreferences sp = JUtils.getSharedPreference();
        User_Phone = sp.getString("User_Phone", "");
        Glide.with(ModifyMeActivity.this).load(headImg)
                .placeholder(R.mipmap.logo)
                .bitmapTransform(new CropCircleTransformation(ModifyMeActivity.this))
                .into(touxiangImg);
        if (SJ_sex.equals("1")) {
            GenderText.setText("男");
        } else {
            GenderText.setText("女");
        }
        CheckBoxString = SJ_sex;
        NameText.setText(SJ_name);
        dianhuaText.setText(User_Phone+"");
    }

    //图片标记
    int successPicCount = 0;//已经成功的个数
    int actualPicCount = 0;//应该成功的个数

    @Override
    public void photoUploadSuccess() {
        successPicCount++;
        modifyme();
        dissmisDialog();

    }

    @OnClick({R.id.actionbar_iv_back, R.id.dianji_Layout, R.id.XM_Layout, R.id.XB_Layout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.actionbar_iv_back:
                finish();
                break;
            case R.id.dianji_Layout:
                selectDialog();
                break;
            case R.id.XM_Layout:
                showCustomizeDialog();
                break;
            case R.id.XB_Layout:
                XBDialog();
                break;
        }
    }

    void modifyme() {
        UserNetWorks.getModifyMe(SJ_name, CheckBoxString, new Subscriber<SmsResponce>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(SmsResponce smsResponce) {
                if (smsResponce.getReturn_code().equals("SUCCESS")) {
                    JUtils.Toast(smsResponce.getReturn_msg());
                } else if (smsResponce.getReturn_code().equals("FAIL")) {
                    JUtils.Toast(smsResponce.getReturn_msg());
                }

            }
        });
    }

    public OssService initOSS(String endpoint, UIDisplayer displayer) {
        OSSCredentialProvider credentialProvider;
        //使用自己的获取STSToken的类
        String bucket = "uu-user";
        String stsServer = "http://api.xn--uu-df3cl18z.com/sts/sts.php";
        if (stsServer.equals("")) {
            credentialProvider = new STSGetter();
        } else {
            credentialProvider = new STSGetter(stsServer);
        }
        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
        conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
        conf.setMaxConcurrentRequest(5); // 最大并发请求书，默认5个
        conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次
        OSS oss = new OSSClient(this, endpoint, credentialProvider, conf);
        return new OssService(oss, bucket, displayer);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            picturePath = cursor.getString(columnIndex);
            Log.d("PickPicture", picturePath);
            cursor.close();
            Glide.with(ModifyMeActivity.this).load(picturePath)
                    .placeholder(R.mipmap.logo)
                    .bitmapTransform(new CropCircleTransformation(ModifyMeActivity.this))
                    .into(touxiangImg);
            displayer.displayInfo("文件: " + picturePath + "\n大小: " + String.valueOf(picturePath.length()));
            startUpload();
        }
    }

    //上传图片
    void startUpload() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date curDate = new Date(System.currentTimeMillis());
        String objectName = "headImg/" + formatter.format(curDate) + "/" + User_Phone + ".png";
        SharedPreferences sp = JUtils.getSharedPreference();
        SharedPreferences.Editor spEd = sp.edit();
        spEd.putString("User_Img", "http://uu-user.oss-cn-beijing.aliyuncs.com/" + objectName);
        spEd.commit();
        ossService.asyncPutImage(objectName, picturePath, User_Phone);
        showDialogNoCancel();
        actualPicCount++;
    }

    void selectDialog() {
        final Dialog bottomDialog = new Dialog(ModifyMeActivity.this, R.style.BottomDialog);
        View contentView = LayoutInflater.from(ModifyMeActivity.this).inflate(R.layout.dialog_photo, null);
        bottomDialog.setContentView(contentView);
        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) contentView.getLayoutParams();
        params.width = getResources().getDisplayMetrics().widthPixels - DensityUtil.dp2px(ModifyMeActivity.this, 16f);
        params.bottomMargin = DensityUtil.dp2px(ModifyMeActivity.this, 8f);
        contentView.setLayoutParams(params);
        bottomDialog.setCanceledOnTouchOutside(true);
        bottomDialog.getWindow().setGravity(Gravity.BOTTOM);
        bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
        bottomDialog.show();

        TextView XiCe_pickPhoto = (TextView) contentView.findViewById(R.id.XiCe_pickPhoto);
        XiCe_pickPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(i, RESULT_LOAD_IMAGE);
                bottomDialog.dismiss();
            }
        });
        TextView XiJi_takePhoto = (TextView) contentView.findViewById(R.id.XiJi_takePhoto);
        XiJi_takePhoto.setVisibility(View.GONE);
        TextView cancel_TextView = (TextView) contentView.findViewById(R.id.cancel_TextView);
        cancel_TextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomDialog.dismiss();
            }
        });

    }

    void XBDialog() {
        final Dialog bottomDialog = new Dialog(ModifyMeActivity.this, R.style.BottomDialog);
        View contentView = LayoutInflater.from(ModifyMeActivity.this).inflate(R.layout.dialog_photo, null);
        bottomDialog.setContentView(contentView);
        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) contentView.getLayoutParams();
        params.width = getResources().getDisplayMetrics().widthPixels - DensityUtil.dp2px(ModifyMeActivity.this, 16f);
        params.bottomMargin = DensityUtil.dp2px(ModifyMeActivity.this, 8f);
        contentView.setLayoutParams(params);
        bottomDialog.setCanceledOnTouchOutside(true);
        bottomDialog.getWindow().setGravity(Gravity.BOTTOM);
        bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
        bottomDialog.show();

        TextView XiCe_pickPhoto = (TextView) contentView.findViewById(R.id.XiCe_pickPhoto);
        XiCe_pickPhoto.setText("男");
        XiCe_pickPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CheckBoxString = "1";
                GenderText.setText("男");
                modifyme();
                bottomDialog.dismiss();

            }
        });
        TextView XiJi_takePhoto = (TextView) contentView.findViewById(R.id.XiJi_takePhoto);
        XiJi_takePhoto.setText("女");
        XiJi_takePhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CheckBoxString = "2";
                GenderText.setText("女");
                modifyme();
                bottomDialog.dismiss();

            }
        });
        TextView cancel_TextView = (TextView) contentView.findViewById(R.id.cancel_TextView);
        cancel_TextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomDialog.dismiss();
            }
        });

    }

    private void showCustomizeDialog() {
    /* @setView 装入自定义View ==> R.layout.dialog_customize
     * 由于dialog_customize.xml只放置了一个EditView，因此和图8一样
     * dialog_customize.xml可自定义更复杂的View
     */
        AlertDialog.Builder customizeDialog =
                new AlertDialog.Builder(ModifyMeActivity.this);
        final View dialogView = LayoutInflater.from(ModifyMeActivity.this)
                .inflate(R.layout.dialog_customize, null);
        customizeDialog.setTitle("请输入姓名");
        customizeDialog.setView(dialogView);
        customizeDialog.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        customizeDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 获取EditView中的输入内容
                        EditText edit_text =
                                (EditText) dialogView.findViewById(R.id.edit_text);
                        SJ_name = edit_text.getText().toString();
                        NameText.setText(SJ_name);
                        modifyme();
                        dialog.dismiss();

                    }
                });
        customizeDialog.show();
    }
}
